class_name MonsterActionPicker
extends Node

var monster: Monster: set = _set_monster
var target: Node2D: set = _set_target

@onready var total_weight := 0.0

var current_action: MonsterAction

func _ready() -> void:
	setup_chances()

func get_action() -> MonsterAction:
	if not current_action:
		current_action = get_children()[0]
		return current_action;
	if current_action.type == MonsterAction.Type.LOOP:
		for action in get_children():
			if action.type != MonsterAction.Type.LOOP:
				continue
			if action.action_id == current_action.get_next_action():
				current_action = action
				return current_action
	if current_action.type == MonsterAction.Type.CHANCE_BASED:
		var roll := randf_range(0.0, total_weight)
		for action in get_children():
			if action.type != MonsterAction.Type.CHANCE_BASED:
				continue
			if action.accumulated_weight >= roll:
				current_action = action
				return current_action
	return null


func _set_monster(value: Monster) -> void:
	monster = value
	for action in get_children():
		action.monster = monster


func _set_target(value: Node2D) -> void:
	target = value
	for action in get_children():
		action.target = target
		
func setup_chances() -> void:
	var action: MonsterAction
	for child in get_children():
		action = child as MonsterAction
		if not action or action.type != MonsterAction.Type.CHANCE_BASED:
			continue
		total_weight += action.chance_weight
		action.accumulated_weight = total_weight
